package com.wmwj.hxlj.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;

import java.util.Date;
import java.util.Map;

public class JWTUtils {
    private static final Logger logger = LoggerFactory.getLogger(JWTUtils.class);

    // 从系统属性中读取密钥和过期时间
    private static final String SECRET_KEY = System.getProperty("jwt.secret.key", "WMWJ");
    private static final long EXPIRATION_TIME = Long.parseLong(System.getProperty("jwt.expiration.time", "604800000")); // 默认7天

    // 缓存 Algorithm 实例以提高性能
    private static final Algorithm ALGORITHM = Algorithm.HMAC256(SECRET_KEY);

    /**
     * 生成JWT令牌
     *
     * @param claims 自定义声明
     * @return 生成的JWT令牌
     */
    public static String getToken(Map<String, Object> claims) {
        return JWT.create()
                .withClaim("claims",claims) // 直接使用 withClaims 方法存储 Map 类型的声明
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .sign(ALGORITHM);
    }

    /**
     * 验证JWT令牌
     *
     * @param token 待验证的JWT令牌
     * @return 验证结果
     */
    public static Map<String, Object> verifyToken(String token) {
            return JWT.require(ALGORITHM)
                .build()
                .verify(token)
                .getClaim("claims")
                .asMap();

    }
}